package com.hmdp.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.CACHE_SHOP_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public Result queryAllTypeList() {
        String key = "cache:shop-type:list" ;
        //1.从redis读取商铺缓存数据
        List<String> dataList = stringRedisTemplate.opsForList().range(key, 0, -1);
        //2.判断缓存是否为空
        if (dataList != null && !dataList.isEmpty()) {
            //3.如果不为空，则返回json格式的数据
            System.out.println("缓存命中，数据："+dataList);
            List<ShopType> shopTypeList = dataList.stream()
                    .map(json -> JSONUtil.toBean(json, ShopType.class)
            ).collect(Collectors.toList());
            return Result.ok(shopTypeList);
        }
        //4.缓存为空，去数据库查数据
        List<ShopType> shopTypes = query().orderByAsc("sort").list();
        //5.判断商铺是否存在
        if (shopTypes.isEmpty() ){
            //6.不存在返回错误给前端
            return Result.fail("商铺类型列表不存在");
        }

        //7.存在，返回商铺数据，并将数据写入redis缓存
        List<String> jsonList = shopTypes.stream()
                .map(JSONUtil::toJsonStr)
                .collect(Collectors.toList());
        stringRedisTemplate.opsForList().rightPushAll(key,jsonList);

        return Result.ok(shopTypes);

    }
}
